package com.adjy.pathbuilders.social;

import java.util.Arrays;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;

import com.adjy.pathbuilders.screens.content.CustomDialog;
import com.adjy.pathbuilders.state.Game;
import com.facebook.Request;
import com.facebook.Request.Callback;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;

public class FacebookConnect extends Activity {

	private Game game;
	private static FacebookConnect instance;
	
	private FacebookConnect() {}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	      super.onActivityResult(requestCode, resultCode, data);
	      this.game.getMainActivity().onActivityResult(requestCode, resultCode, data);
	}
	
	public void setGame(Game game) {
		this.game = game;
	}
	
	public static FacebookConnect getInstance() {
		if(instance == null)
			instance = new FacebookConnect();
		return instance;
	}
	
	public void fbLogIn() {
		// start Facebook Login
	    Session.openActiveSession(this.game.getMainActivity(), true, new 
	    		Session.
	    		StatusCallback() {

	      // callback when session changes state
	      @Override
	      public void call(Session session, SessionState state, Exception exception) {
	        if (session.isOpened()) {

	          // make request to the /me API
	          Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

	            // callback after Graph API response with user object
	            @Override
	            public void onCompleted(GraphUser user, Response response) {
	              if (user != null) {
	                //TextView welcome = (TextView) FacebookConnectScreen.this.game.getActivity().findViewById(R.id.welcome);
	                //welcome.setText
	                System.out.println("Hello " + user.getName() + "!");
	                FacebookConnect.this.game.setFacebookUser(user);
	                FacebookConnect.this.game.getFbConnect().fbLoginListener();
	              } else{
	              }
	            }
	          });
	        }
	      }
	    });
	}
	
	public void fbLogOut() {
		Session.getActiveSession().closeAndClearTokenInformation();
		if(Session.getActiveSession().isClosed()) {
			this.game.setFacebookUser(null);
			FacebookConnect.this.game.getFbConnect().fbLoginListener();
		}
	}
	
	public void fbPostPhoto(Bitmap photo, String description){
		handlePhotoPosted(photo, description, Session.getActiveSession(), Session.getActiveSession().getState(), null);
	}

	private void post(Bitmap photo, String description) {
		
	}
	
	private void handlePhotoPosted(Bitmap photo, String description, Session session, SessionState state, Exception exception) {
//        if(state == SessionState.OPENED_TOKEN_UPDATED) {
//            Callback reqestCallback = new PostPhoto_Callback(photo, description);
//            if(Session.getActiveSession() == null || Session.getActiveSession().isClosed()) return;
//    		if(photo == null) System.out.println("Photo is null!");
//    		Request photoRequest = Request.newUploadPhotoRequest(Session.getActiveSession(), photo, reqestCallback);
//    		Bundle params = photoRequest.getParameters();
//    		params.putString("message", description);
//    		photoRequest.executeAsync();
//        }
        if(Session.getActiveSession() != null && !Session.getActiveSession().getPermissions().contains("publish_actions")){
        	Session.getActiveSession().requestNewPublishPermissions(new Session.NewPermissionsRequest(this.game.getMainActivity(), Arrays.asList("publish_actions")));
        	this.game.getMainActivity().fbPostPhoto(photo, description);
        }else this.game.getMainActivity().fbPostPhoto(photo, description);
    }
	
	private class PostPhoto_Callback implements Request.Callback {
		
		private Bitmap photo;
		private String description;

		public PostPhoto_Callback(Bitmap photo, String description) {
			this.photo = photo;
			this.description = description;
		}
		
		public void call(Session session, SessionState state, Exception exception) {
            Log.d("asd", "photo posted");
            handlePhotoPosted(photo, description, session, state, exception);
        }

		@Override
		public void onCompleted(Response response) {
			call(Session.getActiveSession(), Session.getActiveSession().getState(), null);
			
			if((!Session.getActiveSession().getState().isOpened()) || !Session.getActiveSession().isOpened()){
				System.out.println("PHOTO POSTING ERROR!");
			}
			if(response.getError() != null){
				System.out.println("Did not post... ):");
				Log.e("FRAGACTIVITY", response.getError().toString());
			}else
				System.out.println("The photo was posted! \\o/");
		}
    }

	public void fbPostStatusUpdate() {
		handleSessionStateChanged(Session.getActiveSession(), Session.getActiveSession().getState(), null);
	}
	
	public boolean isLoggedOnFacebook() {
		return Session.getActiveSession() != null && Session.getActiveSession().isOpened();
	}
	
	//FIXME
	private class App_Session_StatusCallback implements Request.Callback {
        public void call(Session session, SessionState state, Exception exception) {
            Log.d("asd", "state changed");
            handleSessionStateChanged(session, state, exception);
        }

		@Override
		public void onCompleted(Response response) {
			call(Session.getActiveSession(), Session.getActiveSession().getState(), null);
		}
    }

    private void handleSessionStateChanged(Session session, SessionState state, Exception exception) {
        if(state == SessionState.OPENED_TOKEN_UPDATED) {
            Callback reqestCallback = new App_Session_StatusCallback();
			Request statusRequest = Request.newStatusUpdateRequest(Session.getActiveSession(), getStatusUpdateText(),  reqestCallback);
            if(statusRequest != null){
                statusRequest.executeAsync();
            }
        }
//        if(session != null) {
//            if(session.isOpened()) {
//                Log.d("asd", "session is opened");
//                Log.d("asd", "Token = " + session.getAccessToken());
//                //Log.d("asd", "Expiry = " + session.getExpirationDate().toGMTString());//FIXME if it's not important, remove it.
//            } else {
//                Log.d("asd", "session is NOT opened");
//            }
//        }
        if(Session.getActiveSession() != null && !Session.getActiveSession().getPermissions().contains("publish_actions"))
        	Session.getActiveSession().requestNewPublishPermissions(new Session.NewPermissionsRequest(this.game.getMainActivity(), Arrays.asList("publish_actions")));
    }

	private String getStatusUpdateText() {
		return CustomDialog.getInstance().getInput();
	}


}
